import React, { useState, useEffect } from 'react';
import { MainMenu } from 'base/ctl/menu';
import { Time } from 'base/ctl/base';
import { DlgLog } from 'base/ctl/log';
import { uPrint, cline, ck_empty, obj_str, loc_dt, obj_int, ck_int, ck_ascii, uDb, IkSelect, obj_float, Wait, ck_float, useForm,
    IkInput, NuiBt, useHigh } from 'sui';
import { loc } from 'local/index';
import { MtTitle, SideBtn, DlgCode } from '../ctl';
import { print_value, load_supply, get_tp } from '../cmd';
import { DlgPrint } from './ctl';

const GBall = ({ umd, wsn, hreturn, cur }) => {
    const [open_menu, openMenu] = useState(false);
    const [open_log, openLog] = useState(false);
    const [open_code, openCode] = useState(false);
    const [open_print, openPrint] = useState(false);
    const [wait, setWait] = useState(false);
    const [info, setInfo] = useState();
    const [err, setErr] = useState();
    const [supply, setSupply] = useState();
    const [high] = useHigh(10, 200)
    const [value, setValue] = useState();
    const form = useForm(setValue);

    useEffect(() => {
        load_supply(cur, setSupply);
        setInfo("提交数据时，会自动生成批次号补码");
        setErr("");
    }, [cur]);

    const hok = () => {
        const mod = get_tp(cur);
        if (!mod) {
            setErr("物料类型不存在");
            return;
        }

        const ck = {
            "sn": (v) => ck_ascii(v),
            "level": (v) => ck_empty(v),
            "supply": (v) => ck_empty(v),
            "ball": (v) => ck_float(v),
            "std": (v) => ck_float(v),
            "sub": (v) => ck_float(v),
            "box": (v) => {
                const e = ck_int(v);
                if (e) {
                    return e;
                }

                const tmp = parseInt(v, 10);
                if (tmp <= 0) {
                    return "盒数必须大于0";
                }

                return null;
            },
            "snum": (v) => {
                const e = ck_int(v);
                if (e) {
                    return e;
                }

                const tmp = parseInt(v, 10);
                if (tmp <= 0) {
                    return "单盒数量必须大于0";
                }

                return null;
            }
        };

        if (!form.hcheck(ck, value)) {
            return;
        }

        const herr = (e) => {
            setWait(false);
            setErr(e);
        };

        setWait(true);

        uDb(null, "code/gen",
            {
                line: cline(),
                rule: "mt",
            },
            r => {
                const bm = obj_str(r, "psn");
                const sn = obj_str(value, "sn") + bm;

                const box = obj_int(value, "box");
                const snum = obj_int(value, "snum");
                const num = box * snum;

                const supply_sn = obj_str(value, "supply");
                const level = obj_str(value, "level");
                const ball = obj_float(value, "ball");
                const std = obj_float(value, "std");
                const sub = obj_float(value, "sub");

                const qr = `${cur}#${supply_sn}#${sn}#${level}*${ball}*${std}*${sub}#${box}#${snum}#${num}`;

                const cmd = {
                    sn: sn,
                    level: level,
                    supply: supply_sn,
                    ball: ball,
                    std: std,
                    sub: sub,
                    state: "ok",
                    box: box,
                    num: num,
                    dnum: num,
                    snum: snum,
                    tmin: loc_dt(new Date()),
                    pos: obj_str(value, "pos"),
                    qr: qr,
                };

                uDb(null, `${mod}/add`,
                    {
                        line: cline(),
                        v: cmd
                    },
                    r => {
                        const cmd = {
                            qr: qr,
                            sn: sn,
                            ball: "" + ball,
                            std: print_value(std),
                            sub: print_value(sub),
                            tmpl: cur.toLowerCase(),
                        };

                        uPrint(null, cmd);

                        for (let i = 1; i < box; i++) {
                            uPrint(null, cmd, null, null, false);
                        }

                        setWait(false);
                        setInfo(`添加物料成功: ${sn}`);
                    },
                    e => herr("添加物料出错"));
            }, e => herr("生成批次码出错"));
    };

    const hcode = (v) => {
        const level = obj_str(v, "level");
        if (!level) {
            v["level"] = "G5";
        }

        setValue(v);
    };

    const menu = [{
        label: "补打标签",
        name: "rprint",
        hcmd: () => openPrint(true),
    }, {
        label: loc("base_157"),
        name: "log",
        hcmd: () => openLog(true),
    }];

    const lst_level = [
        {id: "G3", des: "G3"},
        {id: "G5", des: "G5"},
    ];

    const getView = () => {
        return (
            <div className="flex flex-col">
                <div className="flex flex-col">
                    <div className="bg-white flex flex-col mt-2 mx-4">
                        <div className="bg-green-700 pl-4 text-2xl text-white">批次</div>
                        <div className="inline-flex">
                            <IkInput label="批次号" value={value} form={form} name="sn" className="ml-6 mb-2"/>
                            <IkSelect label="级别" value={value} form={form} name="level" className="ml-4 mb-2" lst={lst_level}/>
                            <IkSelect label="供应商" value={value} form={form} name="supply" className="ml-4 mb-2" lst={supply}/>
                        </div>
                    </div>
                    <div className="bg-white flex flex-col mt-6 mx-4">
                        <div className="bg-green-700 pl-4 text-2xl text-white">规格</div>
                        <div className="inline-flex">
                            <IkInput label="球径" value={value} form={form} name="ball" className="ml-6 mb-2"/>
                            <IkInput label="规值" value={value} form={form} name="std" className="ml-4 mb-2"/>
                            <IkInput label="分规值" value={value} form={form} name="sub" className="ml-4 mb-2"/>
                        </div>
                    </div>
                    <div className="bg-white flex flex-col mt-6 mx-4">
                        <div className="bg-green-700 pl-4 text-2xl text-white">数量与位置</div>
                        <div className="inline-flex">
                            <IkInput label="盒数" value={value} form={form} name="box" className="ml-6 mb-2"/>
                            <IkInput label="单盒数量" value={value} form={form} name="snum" className="ml-4 mb-2"/>
                            <IkInput label="仓位" value={value} form={form} name="pos" className="ml-6 mb-2"/>
                        </div>
                    </div>
                </div>
            </div>
        );
    };

    const getInfo = () => {
        if (err) {
            return <div className="text-red-600">错误： <span className="ml-4">{err}</span></div>;
        }

        return <div className="text-blue-600">{info}</div>;
    };

    return (
        <div className="flex flex-col ml-2 mr-1">
            <div className="inline-flex mt-2 justify-between">
                <div className="inline-flex items-center">
                    <div className="ml-2 mr-4">
                        <MainMenu value={menu} open={open_menu} setOpen={openMenu}/>
                    </div>
                    <MtTitle sub="入库" cur={cur}/>
                </div>
                <Time className="text-2xl"/>
                <NuiBt className="w-32 h-16" hcmd={hreturn}>返回</NuiBt>
            </div>
            <div className="flex flex-row items-start mt-1">
                <div className="flex flex-col w-full">
                    <div className="inline-flex justify-between my-4 mr-1">
                        <div className="w-full bg-gray-200 text-3xl flex items-center justify-center h-32 border border-white">
                            {getInfo()}
                        </div>
                        <SideBtn label="扫码" cl="yellow" hcmd={() => openCode(true)}/>
                        <SideBtn label="提交数据" cl="green" hcmd={hok}/>
                    </div>
                    <div style={{ height: `${high - 250}px`, width: "100%" }} className="my-1 border">
                        {getView()}
                    </div>
                </div>
            </div>
            <DlgLog open={open_log} setOpen={openLog}/>
            <Wait wait={wait}/>
            <DlgCode open={open_code} setOpen={openCode} hcmd={hcode} supply={supply}/>
            <DlgPrint open={open_print} setOpen={openPrint} mt={cur}/>
        </div>
    );
};

export {GBall};
